package cn.hengzhu.main_manager.utils.task;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import cn.hengzhu.main_manager.repository.dao.ErrorLogRecordMapper;
import cn.hengzhu.main_manager.repository.domain.ErrorLogRecord;
import cn.hengzhu.main_manager.repository.domain.ManageUser;
import cn.hengzhu.main_manager.utils.IpAdrrUtil;
import cn.hengzhu.main_manager.utils.UserContext;


/**
 * @author 刘成
 * @since 2018年7月13日
 * 错误日志
 */
@Component
public class AllException implements HandlerExceptionResolver {

	
	@Autowired
	private ErrorLogRecordMapper errorLogRecordMapper;
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception exception) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("ex", exception);
		if (handler instanceof HandlerMethod) {
			String fromUserName = (String) request.getSession().getAttribute("fromUserName");
			ManageUser user = UserContext.getUser();
			// 远程访问IP
			String ip = IpAdrrUtil.getClientIpAddr(request);
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			String className = handlerMethod.getBeanType().getName();
			String methodName = handlerMethod.getMethod().getName();
			StringWriter sw = new StringWriter();
			exception.printStackTrace(new PrintWriter(sw, true));
			
			ErrorLogRecord  errorLogRecord=new ErrorLogRecord();
			errorLogRecord.setClassName(className);
			errorLogRecord.setCreatTime(new Date());
			errorLogRecord.setErrorMsg(sw.toString());
			errorLogRecord.setErrorType(exception.getClass().getSimpleName());
			errorLogRecord.setIp(ip);
			errorLogRecord.setMethodName(methodName);
			if(StringUtils.isNotBlank(fromUserName)){
				errorLogRecord.setUserName(fromUserName);
			}else if(null !=user){
				errorLogRecord.setUserName(user.getLoginName());
			}else{
				return null;
			}
			errorLogRecordMapper.insertSelective(errorLogRecord);
		}
		return null;

	}

}



 